from flask import render_template, request, redirect, url_for, jsonify
from flask import session
from . import index_blu
from models import db
from models.user import User


@index_blu.route('/')
def start_page():
    return redirect(url_for("index.index"))


@index_blu.route("/index.html")
def index():
    # 如果提取到user_id那么就说明用户之前已经登录，否则未登录
    user_id = session.get("user_id")
    if not user_id:
        return render_template('profile.html',user=None)
    # 根据从session中提取到的id，查询数据库
    user = db.session.query(User).filter(User.user_id == user_id).first()
    return render_template('profile.html', user=user)

    # return 返回模板数据（模板文件名为profile.html）


@index_blu.route("/login", methods=["GET", "POST"])
def login():
    user_id = session.get('user_id')
    if user_id:
        return redirect(url_for('index.start_page'))
    if request.method == "POST":
        user_name = request.form.get("Username")
        user_password = request.form.get("Password")

        user = db.session.query(User).filter(User.user_name == user_name, User.user_password == user_password).first()
        if user:
            # 使用session的方式进行状态保持
            session['user_id'] = user.user_id
            # return "登录成功"
            return redirect(url_for("index.index"))
        else:
            return "登录失败..."
    else:
        return render_template("login.html")


@index_blu.route("/logout")
def logout():
    if session.get('user_id'):
        session.clear()
        return redirect(url_for("index.login"))
    else:
        return redirect(url_for('index.start_page'))


@index_blu.route("/register", methods=["GET", "POST"])
def register():
    if request.method == "POST":
        # 如果是POST请求，那么就认为是点击了注册按钮，需要进行注册的业务处理

        # 1. 提取数据
        email = request.form.get("email")
        user_name = request.form.get("user")
        password = request.form.get("password")
        verify = request.form.get("verify")  # 后面再使用

        # 2. 判断数据是否完整
        if not (email and user_name and password):
            # 返回对应的数据
            ret = {
                "status": 1001,
                "errmsg": "输入数据有误，请重新输入"
            }
            return jsonify(ret)

        # 3. 业务处理（注册用户）
        # 判断是否注册过
        ret = db.session.query(User).filter(db.or_(User.email == email, User.user_name == user_name)).first()
        if ret:
            # 如果邮箱或者用户名已经存在，则不允许使用
            # 返回对应的数据
            ret = {
                "status": 1002,
                "errmsg": "邮箱或用户名已存在，请修改"
            }
        else:
            # 如果未注册，那么则进行注册
            user_id = email[:email.find("@")]
            new_user = User(email=email, user_id=user_id, user_password=password, user_name=user_name)
            db.session.add(new_user)
            db.session.commit()

            # 3. 返回对应的数据
            ret = {
                "status": 0,
                "errmsg": "注册成功"
            }

        return jsonify(ret)

    elif request.method == "GET":
        # 如果是GET请求，那么就返回注册页面
        return render_template('register.html')
